const redis = require('redis');
const { REDIS_CONF: { port, host } } = require('../conf/db');

const redisClient = redis.createClient(port, host);
redisClient.on('error', err => {
    console.error(err);
});

function setRedis (key, val) {
    // 如果 redis 的值是个对象，先转换成 JSON
    if (typeof val === 'object') {
        val = JSON.stringify(val);
    }
    redisClient.set(key, val, redis.print);
}

function getRedis (key) {
    return new Promise((resolve, reject) => {
        redisClient.get(key, (err, val) => {
            if (err) {
                reject(err);
                return ;
            }

            if (val == null) {
                resolve(null);
                return ;
            }

            // 使用 try catch 去尝试使用 JSON.parse 转换
            try {
                resolve(JSON.parse(val));
            } catch (e) {
                resolve(val);
            }
        });
    });
}

module.exports = {
    setRedis,
    getRedis
};
